<template>
  <div class="swipeable-image-group">
    <div
      ref="containerRef"
      class="image-container"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
      @mouseleave="handleMouseLeave"
    >
      <div
        class="image-wrapper"
        :style="{ transform: `translateX(${translateX}px)` }"
        @transitionend="handleTransitionEnd"
      >
        <div
          v-for="(item, index) in items"
          :key="index"
          class="image-item"
          :class="{ active: currentIndex === index }"
        >
          <!-- 图片显示 -->
          <n-image
            v-if="isImage(item)"
            :src="processUrl(item.url)"
            :alt="`图片${index + 1}`"
            object-fit="contain"
            class="media-image"
            :preview-src="processUrl(item.url)"
            :show-preview="false"
          />
          <!-- 视频显示 -->
          <div v-else-if="isVideo(item)" class="video-container" @click.stop="previewVideo(item)">
            <video
              :src="processUrl(item.url)"
              class="media-video"
              preload="metadata"
              controls
            />
          </div>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div v-if="items.length > 1" class="navigation-buttons">
        <button
          class="nav-btn prev"
          @click="goToPrevious"
          :disabled="currentIndex === 0"
        >
          <n-icon size="24">
            <ChevronBackIcon />
          </n-icon>
        </button>
        <button
          class="nav-btn next"
          @click="goToNext"
          :disabled="currentIndex === items.length - 1"
        >
          <n-icon size="24">
            <ChevronForwardIcon />
          </n-icon>
        </button>
      </div>

      <!-- 指示器 -->
      <div v-if="items.length > 1" class="indicators">
        <div
          v-for="(item, index) in items"
          :key="index"
          class="indicator"
          :class="{ active: currentIndex === index }"
          @click="goToIndex(index)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { NImage, NIcon } from 'naive-ui'
import { ChevronBack as ChevronBackIcon, ChevronForward as ChevronForwardIcon } from '@vicons/ionicons5'

interface Props {
  items: any[]
  initialIndex?: number
}

interface Emits {
  (e: 'video-preview', item: any): void
}

const props = withDefaults(defineProps<Props>(), {
  initialIndex: 0
})

const emit = defineEmits<Emits>()

const containerRef = ref<HTMLElement>()
const currentIndex = ref(props.initialIndex)
const translateX = ref(0)
const isDragging = ref(false)
const startX = ref(0)
const currentX = ref(0)
const containerWidth = ref(0)

// 处理URL，将HTTPS替换为HTTP
const processUrl = (url: string) => {
  return url.replace(/^https:\/\//, 'http://')
}

// 判断是否为图片
const isImage = (item: any) => {
  const fileType = item.fileType || ''
  return fileType.startsWith('image/') ||
         item.url.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp|bmp)$/)
}

// 判断是否为视频
const isVideo = (item: any) => {
  const fileType = item.fileType || ''
  return fileType.startsWith('video/') ||
         item.url.toLowerCase().match(/\.(mp4|avi|mov|wmv|flv|webm)$/)
}

// 预览视频
const previewVideo = (item: any) => {
  emit('video-preview', item)
}

// 更新位置
const updatePosition = () => {
  translateX.value = -currentIndex.value * containerWidth.value
}

// 切换到指定索引
const goToIndex = (index: number) => {
  if (index >= 0 && index < props.items.length) {
    currentIndex.value = index
    updatePosition()
  }
}

// 上一张
const goToPrevious = () => {
  if (currentIndex.value > 0) {
    goToIndex(currentIndex.value - 1)
  }
}

// 下一张
const goToNext = () => {
  if (currentIndex.value < props.items.length - 1) {
    goToIndex(currentIndex.value + 1)
  }
}

// 触摸事件处理
const handleTouchStart = (e: TouchEvent) => {
  if (props.items.length <= 1) return
  isDragging.value = true
  startX.value = e.touches[0].clientX
  currentX.value = startX.value
}

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return
  e.preventDefault()
  currentX.value = e.touches[0].clientX
  const deltaX = currentX.value - startX.value
  translateX.value = -currentIndex.value * containerWidth.value + deltaX
}

const handleTouchEnd = () => {
  if (!isDragging.value) return
  isDragging.value = false

  const deltaX = currentX.value - startX.value
  const threshold = containerWidth.value * 0.3

  if (Math.abs(deltaX) > threshold) {
    if (deltaX > 0 && currentIndex.value > 0) {
      goToPrevious()
    } else if (deltaX < 0 && currentIndex.value < props.items.length - 1) {
      goToNext()
    } else {
      updatePosition()
    }
  } else {
    updatePosition()
  }
}

// 鼠标事件处理
const handleMouseDown = (e: MouseEvent) => {
  if (props.items.length <= 1) return
  isDragging.value = true
  startX.value = e.clientX
  currentX.value = startX.value
}

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return
  currentX.value = e.clientX
  const deltaX = currentX.value - startX.value
  translateX.value = -currentIndex.value * containerWidth.value + deltaX
}

const handleMouseUp = () => {
  if (!isDragging.value) return
  isDragging.value = false

  const deltaX = currentX.value - startX.value
  const threshold = containerWidth.value * 0.3

  if (Math.abs(deltaX) > threshold) {
    if (deltaX > 0 && currentIndex.value > 0) {
      goToPrevious()
    } else if (deltaX < 0 && currentIndex.value < props.items.length - 1) {
      goToNext()
    } else {
      updatePosition()
    }
  } else {
    updatePosition()
  }
}

const handleMouseLeave = () => {
  if (isDragging.value) {
    handleMouseUp()
  }
}

const handleTransitionEnd = () => {
  // 过渡动画结束后的处理
}

// 键盘事件处理
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'ArrowLeft') {
    goToPrevious()
  } else if (e.key === 'ArrowRight') {
    goToNext()
  }
}

onMounted(() => {
  if (containerRef.value) {
    containerWidth.value = containerRef.value.offsetWidth
    updatePosition()
  }

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (containerRef.value) {
      containerWidth.value = containerRef.value.offsetWidth
      updatePosition()
    }
  })

  // 监听键盘事件
  document.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped>
.swipeable-image-group {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: grab;
}

.image-container:active {
  cursor: grabbing;
}

.image-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
}

.image-item {
  flex-shrink: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.media-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.video-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.media-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.navigation-buttons {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
  padding: 0 16px;
  pointer-events: none;
}

.nav-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  pointer-events: auto;
  transition: background-color 0.3s ease;
}

.nav-btn:hover {
  background: rgba(0, 0, 0, 0.7);
}

.nav-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.indicators {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.indicator.active {
  background: white;
}

.indicator:hover {
  background: rgba(255, 255, 255, 0.8);
}
</style>
